<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>申请总览</span>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="query-form">
      <el-form-item label="学年">
        <el-date-picker
            v-model="queryParams.academicYear"
            type="year"
            placeholder="选择学年"
            clearable
            style="width: 150px"
            value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="学院">
        <el-select v-model="queryParams.collegeId" placeholder="请选择学院" clearable style="width: 200px">
          <el-option 
            v-for="college in collegeList" 
            :key="college.id" 
            :label="college.realName" 
            :value="college.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="success" @click="handleExport">导出数据</el-button>
      </el-form-item>
    </el-form>

    <!-- 申请统计 -->
    <div class="stats-title">申请统计</div>
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-label">申请人数(人)</div>
        <div class="stat-value">{{ applicationStats.allCount || 0 }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-label">已通过审核(人)</div>
        <div class="stat-value success">{{ applicationStats.passedCount || 0 }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-label">未通过审核(人)</div>
        <div class="stat-value danger">{{ applicationStats.rejectedCount || 0 }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-label">审核中(人)</div>
        <div class="stat-value warning">{{ applicationStats.verifyCount || 0 }}</div>
      </el-card>
    </div>

    <!-- 款式数量统计 -->
    <div class="stats-title">款式数量统计</div>
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-label">总款式 (件)</div>
        <div class="stat-value">{{ clothingStats.allCount || 0 }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-label">男款(件)</div>
        <div class="stat-value">{{ clothingStats.manCount || 0 }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-label">女款(件)</div>
        <div class="stat-value">{{ clothingStats.womanCount || 0 }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-label">男女皆宜款(件)</div>
        <div class="stat-value">{{ clothingStats.genderCount || 0 }}</div>
      </el-card>
    </div>

    <!-- 详细表格 -->
    <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px"
        v-loading="loading"
        :span-method="objectSpanMethod"
    >
      <el-table-column prop="academicYear" label="学年" align="center" width="110">
        <template #default="scope">
          {{ formatAcademicYear(scope.row.academicYear) }}
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" width="80">
        <template #default="scope">
          {{ formatGender(scope.row.genderLimit) }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column prop="size" label="尺码" align="center" width="120" />
      <el-table-column prop="count" label="数量" align="center" width="100">
        <template #default="scope">
          <span class="size-count">{{ scope.row.count || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="total" label="共" align="center" width="120">
        <template #default="scope">
          <span class="total-count">共 {{ scope.row.total || 0 }} 件</span>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { _getStatistics, _exportStatistics } from '@/api/statistics'
import { _getUserByRole } from '@/api/user'
import { ElMessage } from 'element-plus'

// 查询参数
const queryParams = ref({
  collegeId: null,
  academicYear: ''
})

// 学院列表
const collegeList = ref([])

// 统计数据
const applicationStats = ref({
  allCount: 0,
  passedCount: 0,
  rejectedCount: 0,
  verifyCount: 0
})

const clothingStats = ref({
  allCount: 0,
  manCount: 0,
  womanCount: 0,
  genderCount: 0
})

const styleStats = ref([])
const loading = ref(false)

// 表格数据（将每个款式的尺码展开成多行）
const tableData = computed(() => {
  const data = []
  styleStats.value.forEach(style => {
    const sizeVos = style.sizeVos || []
    const total = style.count || 0
    
    if (sizeVos.length === 0) {
      // 如果没有尺码数据，显示一行空数据
      data.push({
        academicYear: style.academicYear,
        genderLimit: style.genderLimit,
        name: style.name,
        size: '-',
        count: 0,
        total: total,
        rowspan: 1
      })
    } else {
      // 每个尺码占一行
      sizeVos.forEach((sizeVo, index) => {
        data.push({
          academicYear: style.academicYear,
          genderLimit: style.genderLimit,
          name: style.name,
          size: sizeVo.size,
          count: sizeVo.count,
          total: total,
          rowspan: index === 0 ? sizeVos.length : 0 // 第一行设置 rowspan，其他行设置为 0
        })
      })
    }
  })
  return data
})

// 合并单元格方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 需要合并的列：学年(0)、性别(1)、名称(2)、共(5)
  if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 5) {
    if (row.rowspan > 0) {
      return {
        rowspan: row.rowspan,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

// 格式化学年
const formatAcademicYear = (year) => {
  if (!year) return '-'
  return `${year}-${year + 1}`
}

// 格式化性别
const formatGender = (gender) => {
  const map = {
    0: '女',
    1: '男',
    2: '通用'
  }
  return map[gender] || '-'
}

// 获取学院列表
const getCollegeList = () => {
  _getUserByRole().then(res => {
    if (res.code === 200) {
      collegeList.value = res.data.userList || []
    }
  }).catch(err => {
    console.error('获取学院列表失败:', err)
  })
}

// 获取统计数据
const getStatistics = () => {
  loading.value = true
  
  // 构建查询参数
  const params = {}
  if (queryParams.value.collegeId) {
    params.collegeId = queryParams.value.collegeId
  }
  if (queryParams.value.academicYear) {
    params.academicYear = Number(queryParams.value.academicYear)
  }
  
  _getStatistics(params).then(res => {
    if (res.code === 200) {
      applicationStats.value = res.data.applicationStats || {
        allCount: 0,
        passedCount: 0,
        rejectedCount: 0,
        verifyCount: 0
      }
      clothingStats.value = res.data.clothingStats || {
        allCount: 0,
        manCount: 0,
        womanCount: 0,
        genderCount: 0
      }
      styleStats.value = res.data.styleStats || []
      
      // 计算每个款式的总数
      styleStats.value.forEach(item => {
        let total = 0
        if (item.sizeVos && item.sizeVos.length > 0) {
          item.sizeVos.forEach(sizeVo => {
            total += (sizeVo.count || 0)
          })
        }
        item.count = total
      })
    } else {
      ElMessage.error(res.message || '获取统计数据失败')
    }
  }).catch(err => {
    console.error('获取统计数据失败:', err)
    ElMessage.error('获取统计数据失败')
  }).finally(() => {
    loading.value = false
  })
}

// 查询按钮
const handleQuery = () => {
  getStatistics()
}

// 导出数据
const handleExport = () => {
  const params = {}
  if (queryParams.value.collegeId) {
    params.collegeId = queryParams.value.collegeId
  }
  if (queryParams.value.academicYear) {
    params.academicYear = Number(queryParams.value.academicYear)
  }
  
  ElMessage.info('正在导出数据...')
  
  _exportStatistics(params).then(response => {
    // response.data 是 blob 对象
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 从响应头获取文件名，如果没有则使用默认文件名
    let fileName = '申请统计.xlsx'
    const contentDisposition = response.headers['content-disposition']
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (fileNameMatch && fileNameMatch[1]) {
        fileName = fileNameMatch[1].replace(/['"]/g, '')
      }
    }
    
    link.download = fileName
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  }).catch(err => {
    console.error('导出失败:', err)
    ElMessage.error('导出失败')
  })
}

// 初始化
onMounted(() => {
  getCollegeList()
  getStatistics()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .query-form {
    margin-bottom: 20px;
  }
}

.stats-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin: 20px 0 15px 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 10px;
}

.stat-card {
  text-align: center;
  
  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 10px;
  }
  
  .stat-value {
    font-size: 32px;
    font-weight: bold;
    color: #303133;
    
    &.success {
      color: #67c23a;
    }
    
    &.danger {
      color: #f56c6c;
    }
    
    &.warning {
      color: #e6a23c;
    }
  }
}

.size-count {
  color: #303133;
}

.total-count {
  font-weight: bold;
  color: #303133;
}
</style>

